package com.decent.manager.advice;


import com.decent.common.bo.MessageBean;
import com.decent.common.bo.SimpleMessage;
import com.decent.common.enums.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应信息统一封装管理
 *
 * @author: decent
 * @date: 2021/11/16
 */
@Slf4j
@ControllerAdvice
public class AppResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body instanceof SimpleMessage) {
            log.info("[{}]接口响应[{}]", request.getURI(), body);
            return body;
        }
        if (body instanceof MessageBean) {
            log.info("[{}]接口响应[{}]", request.getURI(), body);
            return body;
        }
        MessageBean result = new MessageBean();
        result.setCode(ErrorCodeEnum.OK.getCode());
        result.setMessage(ErrorCodeEnum.OK.getMessage());
        result.setData(body);
        body = result;
        return body;
    }
}